/* model */
import { 
  BaseSelectUserErrorMessageEnum, 
  BaseSelectUserWarnMessageEnum, 
  SelectUserComponentDepartment, 
  SelectUserComponentUser 
} from '@src/component/common/BaseSelectUser/model'
import MsgModel from '@model/MsgModel'
/* store */
import {
  useBaseSelectUserStoreDepartmentData,
  useBaseSelectUserStoreFetchDepartmentList,
  useBaseSelectUserStoreFetchDepartmentUserList,
  useBaseSelectUserStoreUserCountMap,
  useBaseSelectUserStoreUserListMap,
  useBaseSelectUserStoreFilterForm,
  useBaseSelectUserStoreLoadingMap,
  useBaseSelectUserStoreCurrentDepartmentNav
} from '@src/component/common/BaseSelectUser/store'
/* hooks */
import { useBaseSelectUserOptions } from '@src/component/common/BaseSelectUser/hooks/options'
import { useBaseSelectUserDepartmentListParams, useBaseSelectUserDepartmentUserListParams } from '@src/component/common/BaseSelectUser/hooks/params'
/* util */
import { message } from '@src/util/message'
import { isDisabledSelectItem, setBaseSelectUserListChecked } from '@src/component/common/BaseSelectUser/util'
import Log from '@src/util/log'
/* vue */
import { computed } from 'vue'
/* types */
import { BaseSelectUserGetDepartmentUserListModel, BaseSelectUserGetDepartmentUserListResult } from '@src/component/common/BaseSelectUser/types'
import { isFalse } from '@src/util/type';

/** 
 * @description 选人组件 部门人员列表处理
*/
function useSelectUserDepartmentUserList() {
  
  const { departmentUserList } = useBaseSelectUserStoreUserListMap()
  const { departmentUserCount } = useBaseSelectUserStoreUserCountMap()
  
  // 部门人员列表是否为空
  const isUserListEmpty = computed(() => {
    return departmentUserList.value.length == 0 || departmentUserCount.value == 0
  })
  
  // 部门人员列表是否全部加载完成
  const isUserListAllLoaded = computed(() => {
    return departmentUserList.value.length >= departmentUserCount.value
  })
  
  // 部门人员列表是否未全部加载完成
  const isUserListNotAllLoaded = computed(() => {
    return !isUserListAllLoaded.value
  })
  
  // 是否禁用加载更多人员状态
  const isLoadmoreDisabled = computed(() => {
    
    // 当前人员数量为空时，不禁用加载状态可以加载更多
    if (isUserListEmpty.value) {
      return false
    }
    
    // 全部加载人员后，禁用加载
    return isUserListAllLoaded.value
    
  })
  
  const isLoadmoreNotDisabled = computed(() => isFalse(isLoadmoreDisabled.value))
  
  return {
    isUserListEmpty,
    isUserListAllLoaded,
    isLoadmoreDisabled,
    isLoadmoreNotDisabled,
    isUserListNotAllLoaded
  }
  
}

/** 
 * @description 选人组件 根部门人员列表处理
*/
function useSelectUserDepartmentRootUserList() {
  
  const { departmentRootUserList } = useBaseSelectUserStoreUserListMap()
  const { departmentRootUserCount } = useBaseSelectUserStoreUserCountMap()
  
  // 部门人员列表是否为空
  const isUserListEmpty = computed(() => {
    return departmentRootUserList.value.length == 0 || departmentRootUserCount.value == 0
  })
  
  // 部门人员列表是否全部加载完成
  const isUserListAllLoaded = computed(() => {
    return departmentRootUserList.value.length >= departmentRootUserCount.value
  })
  
  // 部门人员列表是否未全部加载完成
  const isUserListNotAllLoaded = computed(() => {
    return !isUserListAllLoaded.value
  })
  
  // 是否禁用加载更多人员状态
  const isLoadmoreDisabled = computed(() => {
    
    // 当前人员数量为空时，不禁用加载状态可以加载更多
    if (isUserListEmpty.value) {
      return false
    }
    
    // 全部加载人员后，禁用加载
    return isUserListAllLoaded.value
    
  })
  
  const isLoadmoreNotDisabled = computed(() => isFalse(isLoadmoreDisabled.value))
  
  return {
    isUserListEmpty,
    isUserListAllLoaded,
    isLoadmoreDisabled,
    isLoadmoreNotDisabled,
    isUserListNotAllLoaded
  }
  
}

/** 
 * @description 获取选人组件 部门列表
*/
function useFetchDepartmentList() {
  
  const { setDepartmentRootList, departmentRootList } = useBaseSelectUserStoreDepartmentData()
  const { departmentUserListParams } = useBaseSelectUserDepartmentListParams()
  const { isFilterDepartmentFormTagNameEmpty, isFilterDepartmentFormNotEmpty } = useBaseSelectUserStoreFilterForm()
  
  const { setDepartmentRootUserList } = useBaseSelectUserStoreUserListMap()
  const { departmentRootUserCount, setDepartmentRootUserCount } = useBaseSelectUserStoreUserCountMap()
  
  const { setDepartmentLoading, clearDepartmentLoading } = useBaseSelectUserStoreLoadingMap()
  
  const { isLoadmoreDisabled } = useSelectUserDepartmentRootUserList()
  
  const { fetchDepartmentList: optionsFetchDepartmentList } = useBaseSelectUserOptions()
  
  const defaultFetchDepartmentList = useBaseSelectUserStoreFetchDepartmentList()
  
  const fetchDepartmentList = optionsFetchDepartmentList.value || defaultFetchDepartmentList
  
  const fetchDepartmentListImpl = () => {
    
    if (isLoadmoreDisabled.value) {
      Log.warn(BaseSelectUserWarnMessageEnum.DepartmentRootList, fetchDepartmentListImpl.name)
      return Promise.resolve()
    }
    
    setDepartmentLoading()
    
    return (
      fetchDepartmentList(departmentUserListParams.value).then(result => {
        
        if (MsgModel.isSuccess(result)) {
          
          let departmentList = (result?.data || []) as SelectUserComponentDepartment[]
          
          setBaseSelectUserListChecked(departmentList)
          
          const rootDepartment = (departmentList[0] || {}) as SelectUserComponentDepartment
          const rootDepartmentUserCount = (rootDepartment?.userTotalCount || 0) as number
          const rootDepartmentUserList = (rootDepartment?.userList || [])
          
          setDepartmentRootUserCount(rootDepartmentUserCount)
          
          const originDepartmentRoot = (departmentRootList.value[0] || {}) as SelectUserComponentDepartment
          const originDepartmentRootUserList = (originDepartmentRoot?.userList || [])
          
          const isFirstPage = departmentUserListParams.value.pageNum == 1
          // 人员未全部加载完成
          const isUserNotAllLoaded = originDepartmentRootUserList.length < departmentRootUserCount.value
          
          if (isUserNotAllLoaded || isFilterDepartmentFormNotEmpty.value || isFirstPage) {
            
            try {
              // 合并人员互数据
              const allUserList = (
                isFirstPage 
                ? rootDepartmentUserList 
                : originDepartmentRootUserList.concat(rootDepartmentUserList)
              ) as SelectUserComponentUser[]
              
              departmentList[0].userList = allUserList
              
              // 非筛选部门列表，将第一个部门的人员列表设置为根部门人员列表
              if (isFilterDepartmentFormTagNameEmpty.value) {
                departmentList[0].isRoot = true
              }
              
              setDepartmentRootList(departmentList)
              setDepartmentRootUserList(allUserList)
              
            } catch (error) {
              
              Log.error(error, fetchDepartmentListImpl.name)
              
            }
            
          }
          
        } else {
          message.error(result?.message || BaseSelectUserErrorMessageEnum.DepartmentList)
        }
        
      }).finally(() => {
        clearDepartmentLoading()
      })
    )
  }
  
  return fetchDepartmentListImpl
}

/** 
 * @description 获取选人组件 部门/人员 列表
*/
function useFetchDepartmentUserList() {
  
  const { setDepartmentList } = useBaseSelectUserStoreDepartmentData()
  const { setDepartmentUserList, departmentUserList } = useBaseSelectUserStoreUserListMap()
  const { setDepartmentUserCount } = useBaseSelectUserStoreUserCountMap()
  const { setDepartmentUserLoading, clearDepartmentUserLoading } = useBaseSelectUserStoreLoadingMap()
  const { currentDepartmentNav, setCurrentDepartmentNav } = useBaseSelectUserStoreCurrentDepartmentNav()
  
  const { isLoadmoreDisabled } = useSelectUserDepartmentUserList()
  const { departmentUserListParams } = useBaseSelectUserDepartmentUserListParams()
  
  const { fetchDepartmentUserList: optionsFetchDepartmentUserList } = useBaseSelectUserOptions()
  
  const defaultFetchDepartmentUserList = useBaseSelectUserStoreFetchDepartmentUserList()
  
  const fetchDepartmentUserList = (optionsFetchDepartmentUserList.value || defaultFetchDepartmentUserList) as (params: BaseSelectUserGetDepartmentUserListModel) => Promise<MsgModel<BaseSelectUserGetDepartmentUserListResult>>
  
  /** 
   * @description 获取部门/人员 列表
   * 
  */
  const fetchDepartmentUserListImpl = (isInit: boolean = false) => {
    
    if (isLoadmoreDisabled.value && isFalse(isInit)) {
      Log.warn(BaseSelectUserWarnMessageEnum.DepartmentList, fetchDepartmentUserListImpl.name)
      return Promise.resolve()
    }
    
    setDepartmentUserLoading()
    
    return (
      fetchDepartmentUserList(departmentUserListParams.value).then(result => {
        
        if (MsgModel.isSuccess(result)) {
          
          const data = result?.data || {} as BaseSelectUserGetDepartmentUserListResult
          const departmentList = (data?.tagChildren || []) as SelectUserComponentDepartment[]
          const userCount = data?.userTotalCount || 0
          let userList = (data?.userList || []) as SelectUserComponentUser[]
          
          const isFirstPage = departmentUserListParams.value.pageNum == 1
          
          // 合并人员数据
          if (isFalse(isFirstPage)) {
            userList = departmentUserList.value.concat(userList)
          }
          
          setBaseSelectUserListChecked(departmentList)
          setBaseSelectUserListChecked(userList)
          
          setDepartmentUserList(userList)
          setDepartmentUserCount(userCount)
          
        } else {
          message.error(result?.message || BaseSelectUserErrorMessageEnum.DepartmentUserList)
        }
        
      }).finally(() => {
        clearDepartmentUserLoading()
      })
    )
  }
  
  return fetchDepartmentUserListImpl
}

function useFetchDepartmentListAndDepartmentUserList() {
  
  const fetchDepartmentList = useFetchDepartmentList()
  const fetchDepartmentUserList = useFetchDepartmentUserList()
  
  const { departmentRootList, setDepartmentRootList } = useBaseSelectUserStoreDepartmentData()
  const { setDepartmentUserList } = useBaseSelectUserStoreUserListMap()
  const { setCurrentDepartmentNav } = useBaseSelectUserStoreCurrentDepartmentNav()
  const { resetPageNum } = useBaseSelectUserDepartmentUserListParams()
  const { setDepartmentUserCount } = useBaseSelectUserStoreUserCountMap()
  const { clearDepartmentUserLoading } = useBaseSelectUserStoreLoadingMap()
  const { isDepartmentSingle, selected } = useBaseSelectUserOptions()
  
  const fetchRoleListAndRoleUserList = (isResetCurrentDepartmentNav: boolean = true) => {
    
    setDepartmentRootList()
    
    fetchDepartmentList().then(() => {
      // 部门单选 当前选中的部门
      const singleCurrentDepartmentNav = selected.value?.[0] as SelectUserComponentDepartment;

      const firstDepartment = isDepartmentSingle.value ? singleCurrentDepartmentNav : departmentRootList.value[0]
      const isDisabled = isDisabledSelectItem(firstDepartment)
      const isNotDisabled = isFalse(isDisabled)
      
      setDepartmentUserCount()
      setDepartmentUserList()
      
      if (isDisabled) {
        return
      }
      
      if (firstDepartment && isNotDisabled) {
        
        if (isResetCurrentDepartmentNav) {
          setCurrentDepartmentNav(firstDepartment)
        }
        
        resetPageNum()
        setDepartmentUserCount()
        fetchDepartmentUserList()
        
      } else {
        clearDepartmentUserLoading()
      }
      
    })
    
  }
  
  return fetchRoleListAndRoleUserList
}

export {
  useSelectUserDepartmentRootUserList,
  useSelectUserDepartmentUserList,
  useFetchDepartmentList,
  useFetchDepartmentUserList,
  useFetchDepartmentListAndDepartmentUserList
}
